import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository, LessThan, MoreThan } from "typeorm";
import {
  MonthlyCardEntity,
  MonthlyCardType,
  MonthlyCardStatus,
} from "../entities/monthly-card.entity";
import { CharacterService } from "./character.service";
import { TalentStoneService } from "./talent-stone.service";

@Injectable()
export class MonthlyCardService {
  constructor(
    @InjectRepository(MonthlyCardEntity)
    private monthlyCardRepository: Repository<MonthlyCardEntity>,
    private characterService: CharacterService,
    private talentStoneService: TalentStoneService
  ) {}

  /**
   * 查询角色的月卡状态
   */
  async getCharacterMonthlyCards(characterId: number) {
    try {
      const cards = await this.monthlyCardRepository.find({
        where: { characterId },
        order: { cardType: "ASC" },
      });

      // 如果没有月卡记录，创建默认记录
      if (cards.length === 0) {
        return await this.createDefaultMonthlyCards(characterId);
      }

      // 检查月卡是否过期
      const now = new Date();
      for (const card of cards) {
        if (card.status === MonthlyCardStatus.ACTIVE && card.expiresAt < now) {
          card.status = MonthlyCardStatus.EXPIRED;
          card.over = 1;
          await this.monthlyCardRepository.save(card);
        }

        // 检查每日奖励是否可领取
        if (card.status === MonthlyCardStatus.ACTIVE) {
          const today = new Date();
          today.setHours(0, 0, 0, 0);
          const lastReward = new Date(card.lastDailyRewardAt);
          lastReward.setHours(0, 0, 0, 0);

          if (today.getTime() !== lastReward.getTime()) {
            // 新的一天，重置每日领取状态
            card.todayRewardClaimed = 0;
            // 注意：不修改stage字段，stage表示月卡购买状态，不是每日领取状态
            await this.monthlyCardRepository.save(card);
          }
        }
      }

      return cards;
    } catch (error) {
      console.error("查询月卡状态失败:", error);
      throw error;
    }
  }

  /**
   * 创建默认月卡记录
   */
  private async createDefaultMonthlyCards(characterId: number) {
    const now = new Date();
    const defaultCards = [
      {
        characterId,
        cardType: MonthlyCardType.SMALL,
        status: MonthlyCardStatus.INACTIVE,
        stage: 0,
        over: 0,
        purchasedAt: now,
        activatedAt: now,
        expiresAt: now,
        lastDailyRewardAt: now,
        todayRewardClaimed: 0,
        consecutiveDays: 0,
        totalDays: 0,
        price: 0,
        remark: "小月卡",
        created_at: now,
        updated_at: now,
      },
      {
        characterId,
        cardType: MonthlyCardType.LARGE,
        status: MonthlyCardStatus.INACTIVE,
        stage: 0,
        over: 0,
        purchasedAt: now,
        activatedAt: now,
        expiresAt: now,
        lastDailyRewardAt: now,
        todayRewardClaimed: 0,
        consecutiveDays: 0,
        totalDays: 0,
        price: 0,
        remark: "大月卡",
        created_at: now,
        updated_at: now,
      },
    ];

    const savedCards = await this.monthlyCardRepository.save(defaultCards);
    return savedCards;
  }

  /**
   * 购买月卡
   */
  async purchaseMonthlyCard(characterId: number, cardType: MonthlyCardType) {
    try {
      // 检查角色是否存在
      const character = await this.characterService.getCharacterById(
        characterId
      );
      if (!character) {
        throw new Error("角色不存在");
      }

      // 获取角色资源信息
      const resources = await this.characterService.getCharacterResources(
        characterId
      );
      if (!resources) {
        throw new Error("角色资源信息不存在");
      }

      const price = this.getMonthlyCardPrice(cardType);
      if (resources.gold < price) {
        throw new Error("金币不足");
      }

      // 查找现有月卡记录
      let monthlyCard = await this.monthlyCardRepository.findOne({
        where: { characterId, cardType },
      });

      if (!monthlyCard) {
        throw new Error("月卡记录不存在");
      }

      // 检查是否已经购买
      if (monthlyCard.stage >= 1) {
        throw new Error("月卡已购买");
      }

      // 扣除金币
      await this.characterService.updateCharacterResources(characterId, {
        gold: -price,
      });

      // 更新月卡状态
      const now = new Date();
      const expiresAt = new Date();
      expiresAt.setDate(expiresAt.getDate() + 30); // 30天有效期

      monthlyCard.stage = 1;
      monthlyCard.status = MonthlyCardStatus.ACTIVE;
      monthlyCard.purchasedAt = now;
      monthlyCard.activatedAt = now;
      monthlyCard.expiresAt = expiresAt;
      monthlyCard.price = price;
      monthlyCard.updated_at = now;

      const savedCard = await this.monthlyCardRepository.save(monthlyCard);

      return {
        success: true,
        card: savedCard,
        message: "月卡购买成功",
      };
    } catch (error) {
      console.error("购买月卡失败:", error);
      throw error;
    }
  }

  /**
   * 领取每日奖励
   */
  async claimDailyReward(characterId: number, cardType: MonthlyCardType) {
    try {
      const monthlyCard = await this.monthlyCardRepository.findOne({
        where: { characterId, cardType },
      });

      if (!monthlyCard) {
        throw new Error("月卡记录不存在");
      }

      if (monthlyCard.status !== MonthlyCardStatus.ACTIVE) {
        throw new Error("月卡未激活");
      }

      if (monthlyCard.over === 1) {
        throw new Error("月卡已过期");
      }

      // 检查是否是新的一天：如果跨日，先重置 todayRewardClaimed
      const now = new Date();
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const lastReward = new Date(monthlyCard.lastDailyRewardAt);
      lastReward.setHours(0, 0, 0, 0);

      if (today.getTime() !== lastReward.getTime()) {
        // 跨天自动重置今日领取标志
        monthlyCard.todayRewardClaimed = 0;
      }

      if (monthlyCard.todayRewardClaimed === 1) {
        throw new Error("今日奖励已领取");
      }

      // 计算奖励
      const reward = this.calculateDailyReward(cardType);

      // 发放奖励
      await this.characterService.updateCharacterResources(characterId, reward);

      // 发放天赋石奖励
      let talentStones: any[] = [];
      if (reward.talentStones && reward.talentStones > 0) {
        try {
          talentStones = await this.talentStoneService.createRandomTalentStones(
            characterId,
            reward.talentStones
          );
          console.log(
            `月卡每日奖励：为角色${characterId}发放了${reward.talentStones}个1级天赋石`
          );
        } catch (error) {
          console.error("发放天赋石奖励失败:", error);
          // 天赋石发放失败不影响其他奖励的发放
        }
      }

      // 更新月卡状态
      monthlyCard.todayRewardClaimed = 1;
      // 注意：不修改stage字段，stage表示月卡购买状态，不是每日领取状态
      monthlyCard.lastDailyRewardAt = now;
      monthlyCard.totalDays += 1;
      monthlyCard.updated_at = now;

      // 检查连续领取
      const yesterday = new Date(today);
      yesterday.setDate(yesterday.getDate() - 1);
      if (lastReward.getTime() === yesterday.getTime()) {
        monthlyCard.consecutiveDays += 1;
      } else {
        monthlyCard.consecutiveDays = 1;
      }

      const savedCard = await this.monthlyCardRepository.save(monthlyCard);

      return {
        success: true,
        card: savedCard,
        reward: {
          ...reward,
          talentStones: talentStones.map((stone) => ({
            id: stone.id,
            name: stone.name,
            level: stone.level,
            type: stone.type,
            description: stone.description,
          })),
        },
        message: "每日奖励领取成功",
      };
    } catch (error) {
      console.error("领取每日奖励失败:", error);
      throw error;
    }
  }

  /**
   * 重置当日领取状态（测试用）
   * 将 todayRewardClaimed 置为 0，并将 lastDailyRewardAt 回退到前一天
   * @param characterId 角色ID
   * @param cardType 可选，指定重置的卡种；不传则重置该角色全部月卡
   * @returns 被重置的记录数量
   */
  async resetDailyRewardStatus(
    characterId: number,
    cardType?: MonthlyCardType
  ): Promise<number> {
    const where: any = { characterId };
    if (cardType !== undefined && cardType !== null) {
      where.cardType = cardType;
    }

    const cards = await this.monthlyCardRepository.find({ where });
    if (cards.length === 0) return 0;

    const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000);
    let count = 0;
    for (const card of cards) {
      card.todayRewardClaimed = 0;
      card.lastDailyRewardAt = yesterday;
      card.updated_at = new Date();
      await this.monthlyCardRepository.save(card);
      count += 1;
    }
    return count;
  }

  /**
   * 获取月卡价格
   */
  private getMonthlyCardPrice(cardType: MonthlyCardType): number {
    switch (cardType) {
      case MonthlyCardType.SMALL:
        return 13000; // 小月卡13000金币
      case MonthlyCardType.LARGE:
        return 33000; // 大月卡33000金币
      default:
        return 0;
    }
  }

  /**
   * 计算每日奖励
   */
  private calculateDailyReward(cardType: MonthlyCardType) {
    switch (cardType) {
      case MonthlyCardType.SMALL:
        return {
          gold: 20000, // 小月卡：金币
          silver: 500000, // 50万银子
          talentStones: 2, // 小月卡每天赠送2个1级天赋石
        };
      case MonthlyCardType.LARGE:
        return {
          gold: 100000, // 大月卡：金币
          silver: 1000000, // 100万银子
          talentStones: 5, // 大月卡每天赠送5个1级天赋石
        };
      default:
        return {};
    }
  }

  /**
   * 检查月卡是否有效
   */
  async isMonthlyCardValid(
    characterId: number,
    cardType: MonthlyCardType
  ): Promise<boolean> {
    try {
      const monthlyCard = await this.monthlyCardRepository.findOne({
        where: { characterId, cardType },
      });

      if (!monthlyCard) {
        return false;
      }

      if (monthlyCard.status !== MonthlyCardStatus.ACTIVE) {
        return false;
      }

      if (monthlyCard.over === 1) {
        return false;
      }

      const now = new Date();
      return monthlyCard.expiresAt > now;
    } catch (error) {
      console.error("检查月卡有效性失败:", error);
      return false;
    }
  }

  /**
   * 格式化月卡数据为前端期望的格式
   */
  formatMonthlyCardsForFrontend(cards: MonthlyCardEntity[]) {
    const now = new Date();
    const formattedCards = cards.map((card) => {
      // 计算剩余天数
      const timeDiff = card.expiresAt.getTime() - now.getTime();
      const daysLeft = Math.max(
        0,
        Math.floor(timeDiff / (1000 * 60 * 60 * 24))
      );

      // 检查今日是否已领取
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const lastReward = new Date(card.lastDailyRewardAt);
      lastReward.setHours(0, 0, 0, 0);
      const canClaimToday =
        today.getTime() !== lastReward.getTime() &&
        card.status === MonthlyCardStatus.ACTIVE;

      // 根据todayRewardClaimed字段计算前端需要的stage值
      let frontendStage = card.stage; // 默认使用数据库的stage值

      if (card.stage >= 1) {
        // 月卡已购买/激活
        if (card.todayRewardClaimed === 1) {
          frontendStage = 2; // 今日已领取
        } else {
          frontendStage = 1; // 可领取
        }
      }

      return {
        card: card.cardType.toString(), // 前端期望字符串格式 "38" 或 "98"
        stage: frontendStage, // 0=未激活, 1=可领取, 2=已领取
        over: card.expiresAt.getTime(), // 过期时间戳(毫秒)
        todayRewardClaimed: card.todayRewardClaimed, // 今日是否已领取奖励
        consecutiveDays: card.consecutiveDays, // 连续领取天数
        totalDays: card.totalDays, // 总领取天数
      };
    });

    return formattedCards;
  }

  /**
   * 获取角色月卡数据（前端格式）
   */
  async getCharacterMonthlyCardsForFrontend(characterId: number) {
    try {
      const cards = await this.getCharacterMonthlyCards(characterId);
      return this.formatMonthlyCardsForFrontend(cards);
    } catch (error) {
      console.error("获取角色月卡数据失败:", error);
      throw error;
    }
  }
}
